package com.tiza.xiaoyoubao.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tianze.library.utils.AppUtils;
import com.tianze.library.utils.DateUtils;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.AppConfig;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.view.SpacingTextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

public class RegisterFragment extends BaseFragment {
    //获取验证码
    @BindView(R.id.btn_verify)
    Button btn_verify;
    //用户名
    @BindView(R.id.et_phone)
    EditText et_phone;
    //密码
    @BindView(R.id.et_passWord)
    EditText et_passWord;
    //密码确认
    @BindView(R.id.et_confirmPasswd)
    EditText et_confirmPasswd;
    //验证码
    @BindView(R.id.et_verify)
    EditText et_verify;
    //邀请码
    @BindView(R.id.et_inviteCode)
    EditText et_inviteCode;
    //服务协议
    @BindView(R.id.iv_Select)
    ImageView iv_Select;
    @BindView(R.id.tv_waring)
    TextView tv_waring;

    private String userName;
    private String passWord;
    //邀请码
    private String inviteCode = "";
    //输入的短信验证码
    private String userVerify;
    //获取的短信验证码
    private String verifyCode = "";
    //是否同意协议
    private boolean isSelect = false;
    private static final int SECONDS = 60;

    private int nowSeconds = SECONDS;

    private static Handler sHandler = new Handler();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (nowSeconds >= 2) {
                nowSeconds--;
                btn_verify.setText(nowSeconds + "s后重发");
                sHandler.postDelayed(this, 1000);
            } else {
                nowSeconds = SECONDS;
                btn_verify.setText("获取验证码");
                btn_verify.setEnabled(true);
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_register;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        SpannableString spannableString = new SpannableString(
                mActivity.getString(R.string.text_warning));
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#ff0000"));
        spannableString.setSpan(colorSpan, 15, spannableString.length() - 19,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        );
        tv_waring.setText(spannableString);
        //tv_waring.setLetterSpacing(5);
    }

    @Override
    protected void initView() {


    }

    @OnClick({R.id.btn_verify, R.id.btn_register, R.id.iv_Select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_verify:
                int i=AppConfig.getSendVerTime();
                Log.i("time", "今天发送短信的次数：" +i);
                userName = et_phone.getText().toString();
                if (AppUtils.isMobile(userName)) {
                    if (com.tiza.xiaoyoubao.utils.DateUtils.getDaySub(format.format(new Date()), AppConfig.getSendVerDate()) == 0) {
                        Log.i("time", "今天发送短信的次数a：" + i);
                        if (AppConfig.getSendVerTime() == 6) {
                            Log.i("time", "今天发送短信的最大次数：" + i);
                            AppConfig.setSendVerDate(format.format(com.tiza.xiaoyoubao.utils.DateUtils.nextDate(new Date(), 1)));
                            toast("已达到今日获取验证码的最大限制");
                            return;
                        }else{
                            doVerify();
                        }
                    }else{
                        AppConfig.setSendVerTime(1);
                        toast("已达到今日获取验证码的最大限制");
                        return;
                    }
                } else {
                    showWarnDialog("请输入正确的手机号");
                }
                break;
            case R.id.btn_register:
                String message = checkRegister();
                if (TextUtils.isEmpty(message)) {
                    register();
                } else {
                    showWarnDialog(message);
                }
                break;
            case R.id.iv_Select:
                if (!isSelect) {
                    iv_Select.setImageResource(R.mipmap.landuihao);
                    isSelect = true;
                } else {
                    iv_Select.setImageResource(R.mipmap.baiduihao);
                    isSelect = false;
                }
                break;
            default:
                break;
        }
    }

    private String checkRegister() {
        inviteCode = et_inviteCode.getText().toString();
        userName = et_phone.getText().toString().trim();
        if (!AppUtils.isMobile(userName))
            return "请输入正确的手机号";
        userVerify = et_verify.getText().toString().trim();
        if (TextUtils.isEmpty(userVerify))
            return "请输入验证码";
        if (!verifyCode.equals(userVerify) || TextUtils.isEmpty(verifyCode))
            return "验证码有误";
        passWord = et_passWord.getText().toString().trim();
        if (passWord.length() == 0)
            return "请输入密码";
        String confirmPasswd = et_confirmPasswd.getText().toString().trim();
        if (confirmPasswd.length() == 0)
            return "请输入验证密码";
        if (!passWord.equals(confirmPasswd))
            return "两次输入密码不一致";
        if (!isSelect)
            return "请同意小优宝服务协议";
        return "";
    }


    private void doVerify() {
        btn_verify.setEnabled(false);
        sHandler.post(runnable);
        ApiHttpClient.verify(RegisterFragment.this, userName,
                new JsonCallback<String>(String.class, true) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("验证码获取失败");
                        sHandler.removeCallbacks(runnable);
                        nowSeconds = SECONDS;
                        btn_verify.setText("获取验证码");
                        btn_verify.setEnabled(true);
                    }

                    @Override
                    public void onResponse(ResponseInfo<String> response) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            sHandler.removeCallbacks(runnable);
                            nowSeconds = SECONDS;
                            btn_verify.setText("获取验证码");
                            btn_verify.setEnabled(true);
                            return;
                        }
                        Map<String, Object> _map = response.getFirstEntity();
                        verifyCode = String.valueOf(_map.get("verify"));
                        int time = AppConfig.getSendVerTime();
                        Log.i("RegisterFragment", "发送信息验证码次数" + time);
                        AppConfig.setSendVerTime(time+1);
                        AppConfig.setSendVerDate(format.format(new Date()));
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    private void register() {
        btn_verify.setEnabled(false);
        ApiHttpClient.register(RegisterFragment.this, userName, passWord, inviteCode,
                new JsonCallback<String>(String.class, true) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        showWaitingDialog();
                    }

                    @Override
                    public void onResponse(ResponseInfo<String> response) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        toast("注册成功!");
                        // 保存用户名,密码
                        Hawk.put(Constants.KEY_USER_NAME, userName);
                        Hawk.put(Constants.KEY_USER_PASSWD, passWord);
                        UIHelper.showLogin(getActivity());
                        finish();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sHandler.removeCallbacks(runnable);
    }
}
